package xps.and.uudaijia.userclient.view.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.mapapi.search.core.PoiInfo;
import com.hitomi.cslibrary.CrazyShadow;
import com.hitomi.cslibrary.base.CrazyShadowDirection;
import com.jude.utils.JUtils;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import nucleus.factory.RequiresPresenter;
import rx.Subscriber;
import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.EventBusCommond.EventBusRequestReserveTime;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.StringCommond;
import xps.and.uudaijia.userclient.data.baen.DoubleBean;
import xps.and.uudaijia.userclient.data.baen.DudgetBean;
import xps.and.uudaijia.userclient.data.baen.ReservationBean;
import xps.and.uudaijia.userclient.data.baen.VehicleBean;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.presenter.DaijiaInfoPanelFragmentPresenter;
import xps.and.uudaijia.userclient.util.DateTimePickDialogUtilDaijia;
import xps.and.uudaijia.userclient.util.GlobalPositionInfo;
import xps.and.uudaijia.userclient.util.JingtouBack;
import xps.and.uudaijia.userclient.view.MainActivity;
import xps.and.uudaijia.userclient.view.activity.MapViewActivity;
import xps.and.uudaijia.userclient.view.activity.ObtainAddressActivty;
import xps.and.uudaijia.userclient.view.activity.YHJSYActivity;
import xps.and.uudaijia.userclient.view.base.BaseFragment;

@RequiresPresenter(DaijiaInfoPanelFragmentPresenter.class)
public class DaijiaInfoPanelFragment extends BaseFragment<DaijiaInfoPanelFragmentPresenter> {
    @BindView(R.id.tv_reservation_time)
    public TextView tvReservationTime;
    @BindView(R.id.tv_employ_time)
    public TextView tvEmployTime;
    @BindView(R.id.rb_five_hours)
    public RadioButton rbFiveHours;
    @BindView(R.id.rb_a_day)
    public RadioButton rbADay;
    @BindView(R.id.rg_contract_period)
    public RadioGroup rgContractPeriod;
    @BindView(R.id.et_phone_number)
    public EditText etPhoneNumber;
    @BindView(R.id.tv_start_location)
    public TextView tvStartLocation;
    @BindView(R.id.tv_end_location)
    public TextView tvEndLocation;
    @BindView(R.id.tv_trival_cost)
    public TextView tvTrivalCost;
    @BindView(R.id.a)
    public AutoLinearLayout a;
    @BindView(R.id.bt_publish_order)
    public Button btPublishOrder;
    @BindView(R.id.al_reservation_time)
    public AutoLinearLayout alReservationTime;
    @BindView(R.id.al_contract_period)
    public AutoLinearLayout alContractPeriod;
    @BindView(R.id.al_phone_number)
    public AutoLinearLayout alPhoneNumber;
    @BindView(R.id.al_start_location)
    public AutoLinearLayout alStartLocation;
    @BindView(R.id.al_end_location)
    public AutoLinearLayout alEndLocation;
    @BindView(R.id.line_contract_driver)
    public View lineContractDriver;
    @BindView(R.id.line_phone_number)
    public View linePhoneNumber;
    Unbinder unbinder;
    @BindView(R.id.tv_call_forSelf)
    TextView tvCallForSelf;
    @BindView(R.id.tv_call_forOthers)
    TextView tvCallForOthers;
    @BindView(R.id.tv_contractToDriver)
    TextView tvContractToDriver;
    public static int OBTAIN_START = 0;
    public static int OBTAIN_END = 1;
    public String startLng = "";
    public String startLat = "";
    String endLng = "";
    String endLat = "";
    CrazyShadow shadowContractToDriver;
    CrazyShadow shadowCallForOthers;
    CrazyShadow shadowCallForSelf;
    String dat;
    public String access_token = "";
    public String userid = "";
    Calendar calendar = Calendar.getInstance();//来自时间选择控件
    String startTimeStamp;
    String GYDate = "5";
    String endLngStr = "";
    String endLatStr = "";
    String tvEndLoca = "";
    @BindView(R.id.YHJ_Layout)
    AutoRelativeLayout YHJLayout;
    public String couponId;
    @BindView(R.id.YHJ_Text)
    public TextView YHJText;
    boolean PD = true;
    @BindView(R.id.beishu_Text)
    TextView beishuText;
    String beishu;
    @BindView(R.id.bei_Text)
    TextView beiText;
    JingtouBack call;

    @Override
    protected int getRes() {
        return R.layout.fragment_daijia_info_panle;
    }

    @Override
    protected void init(View view) {
        unbinder = ButterKnife.bind(this, view);
        beiText.setVisibility(View.GONE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        tvCallForSelf.setTextColor(getResources().getColor(R.color.white));
        toTypeA();
        initFunctionLable();
        shadowCallForSelf.show();
        access_token = getArguments().getString("access_token");
        userid = getArguments().getString("userid");
        rbFiveHours.setChecked(true);
        rgContractPeriod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rbFiveHours.getId()) {
                    GYDate = "5";
                    getDudget();
                } else if (checkedId == rbADay.getId()) {
                    GYDate = "10";
                    getDudget();
                }
            }
        });
        call = (JingtouBack) getActivity();
    }

    public void hide() {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.hide(this);
        fragmentTransaction.commit();
    }

    //为自己叫
    public void toTypeA() {
        reset();
        PD = true;
        lineContractDriver.setVisibility(View.GONE);
        linePhoneNumber.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventMainThread(EventBusRequestReserveTime commond) {
        if (commond.getFrom().equals(EventBusRequestReserveTime.FROM_DAIJIA)) {
            Log.e("DaijiaInfoPanelFragment", commond.getFrom());
        }
    }

    //为别人叫
    public void toTypeB() {
        reset();
        PD = true;
        alPhoneNumber.setVisibility(View.VISIBLE);
        lineContractDriver.setVisibility(View.GONE);
        linePhoneNumber.setVisibility(View.VISIBLE);
    }

    //雇司机
    public void toTypeC() {
        reset();
        PD = false;
        alContractPeriod.setVisibility(View.VISIBLE);
        lineContractDriver.setVisibility(View.VISIBLE);
        linePhoneNumber.setVisibility(View.GONE);
    }

    private void reset() {
        alContractPeriod.setVisibility(View.GONE);
        alPhoneNumber.setVisibility(View.GONE);
    }

    @Override
    protected void setData(View view) {
        getReservation();//
    }

    @OnClick({R.id.tv_call_forSelf, R.id.tv_call_forOthers, R.id.tv_contractToDriver, R.id.tv_start_location})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_call_forSelf:
                toTypeA();
                resetCallTypeLable();
                shadowCallForSelf.show();
                tvCallForSelf.setTextColor(getResources().getColor(R.color.white));
                EventBus.getDefault().post(StringCommond.ON_GLOBALLAYOUT_CHANGES);
                getReservation();
                break;
            case R.id.tv_call_forOthers:
                toTypeB();
                resetCallTypeLable();
                shadowCallForOthers.show();
                tvCallForOthers.setTextColor(getResources().getColor(R.color.white));
                EventBus.getDefault().post(StringCommond.ON_GLOBALLAYOUT_CHANGES);
                getReservation();
                break;
            case R.id.tv_contractToDriver:
                toTypeC();
                resetCallTypeLable();
                shadowContractToDriver.show();
                tvContractToDriver.setTextColor(getResources().getColor(R.color.white));
                EventBus.getDefault().post(StringCommond.ON_GLOBALLAYOUT_CHANGES);
                getDudget();
                break;
        }
    }

    /**
     * 初始化 服务类型按钮的阴影
     */
    void initFunctionLable() {
        shadowCallForSelf = new CrazyShadow.Builder()
                .setContext(getActivity())
                .setDirection(CrazyShadowDirection.ALL)
                .setShadowRadius(JUtils.dip2px(3))
                .setCorner(JUtils.dip2px(10))
                .setBackground(getResources().getColor(R.color.colorPrimary))
                .setImpl(CrazyShadow.IMPL_DRAW)
                .action(tvCallForSelf);
        shadowCallForSelf.hide();
        tvCallForSelf.setTextColor(getResources().getColor(R.color.white));

        shadowCallForOthers = new CrazyShadow.Builder()
                .setContext(getActivity())
                .setDirection(CrazyShadowDirection.ALL)
                .setShadowRadius(JUtils.dip2px(3))
                .setCorner(JUtils.dip2px(10))
                .setBackground(getResources().getColor(R.color.colorPrimary))
                .setImpl(CrazyShadow.IMPL_DRAW)
                .action(tvCallForOthers);
        shadowCallForOthers.hide();
        tvCallForOthers.setTextColor(getResources().getColor(R.color.black));

        shadowContractToDriver = new CrazyShadow.Builder()
                .setContext(getActivity())
                .setDirection(CrazyShadowDirection.ALL)
                .setShadowRadius(JUtils.dip2px(3))
                .setCorner(JUtils.dip2px(10))
                .setBackground(getResources().getColor(R.color.colorPrimary))
                .setImpl(CrazyShadow.IMPL_DRAW)
                .action(tvContractToDriver);
        shadowContractToDriver.hide();
        tvContractToDriver.setTextColor(getResources().getColor(R.color.black));
    }

    void resetCallTypeLable() {
        shadowCallForSelf.hide();
        shadowCallForOthers.hide();
        shadowContractToDriver.hide();
        tvCallForSelf.setTextColor(getResources().getColor(R.color.black));
        tvCallForOthers.setTextColor(getResources().getColor(R.color.black));
        tvContractToDriver.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @OnClick({R.id.bt_publish_order, R.id.al_start_location, R.id.YHJ_Layout, R.id.al_end_location, R.id.tv_reservation_time, R.id.tv_employ_time, R.id.tv_start_location, R.id.tv_end_location})
    public void onViewClicked(View v) {

        switch (v.getId()) {
            case R.id.bt_publish_order:
                if (tvStartLocation.getText().toString().equals("正在获取位置...")) {
                    JUtils.Toast("请重新选择起点位置");
                } else {
                    getDouble();
                }
                break;
            case R.id.tv_reservation_time:
                // EventBus.getDefault().post(StringCommond.ON_REQUEST_RESERVETIME_DAIJIAFRAGMENT);
                GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
                dat = tvReservationTime.getText().toString();
                if (dat.equals("立即出发")) {//获取当前时间
                    Date curDate = new Date(System.currentTimeMillis() + 5000);//当前时间的 一秒 后
                    startTimeStamp = curDate.getTime() / 1000 + "";
                } else {
                    startTimeStamp = calendar.getTime().getTime() / 1000 + "";//否则使用已选择的时间
                }
                DateTimePickDialogUtilDaijia dateTimePicKDialog = new DateTimePickDialogUtilDaijia(
                        getActivity(), startTimeStamp, tvReservationTime, new DateTimePickDialogUtilDaijia.OnPickerListener() {
                    @Override
                    public void onConfirm(Calendar calendar) {
                        DaijiaInfoPanelFragment.this.calendar = calendar;
                        if (alContractPeriod.getVisibility() == View.GONE) {
                            getReservation();
                        } else {
                            getDudget();
                        }
                    }

                    @Override
                    public void onDismiss() {

                    }
                });
                dateTimePicKDialog.dateTimePicKDialog();
                break;
            case R.id.tv_employ_time:

                break;
            case R.id.tv_start_location:
                Intent intentObtainStart = new Intent(getActivity(), ObtainAddressActivty.class);
                startActivityForResult(intentObtainStart, OBTAIN_START);
                break;

            case R.id.tv_end_location:
                Intent intentObtainEnd = new Intent(getActivity(), ObtainAddressActivty.class);
                startActivityForResult(intentObtainEnd, OBTAIN_END);
                break;
            case R.id.YHJ_Layout:
                Intent YHJSYintent = new Intent(getActivity(), YHJSYActivity.class);
                startActivity(YHJSYintent);
                break;
        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == OBTAIN_START) {
            PoiInfo poi = data.getParcelableExtra(ObtainAddressActivty.RESPONCE);
            tvStartLocation.setText(poi.name);
            startLat = poi.location.latitude + "";
            startLng = poi.location.longitude + "";

            call.getShuzhiBack(poi.location.latitude, poi.location.longitude);
        } else if (requestCode == OBTAIN_END) {
            PoiInfo poi = data.getParcelableExtra(ObtainAddressActivty.RESPONCE);
            tvEndLocation.setText(poi.name);
            endLng = poi.location.longitude + "";
            endLat = poi.location.latitude + "";
        }
        if (alContractPeriod.getVisibility() == View.GONE) {
            getReservation();
        } else {
            getDudget();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (alContractPeriod.getVisibility() == View.GONE) {
            getReservation();
        } else {
            getDudget();
        }
    }

    public void getDudget() {
        UserNetWorks.getDudget(GYDate, startLng, startLat, endLng, endLat, new Subscriber<DudgetBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(DudgetBean dudgetBean) {
                DudgetBean.ReturnBodyBean reservation = dudgetBean.getReturn_body();
                if (dudgetBean.getReturn_code().equals("SUCCESS")) {
                    if (reservation.getIsFareIncrease().equals("1")) {
                        tvTrivalCost.setText(reservation.getPrice() + "元 X");
                        beishuText.setText("" + reservation.getFareIncreaseRate() + "");
                        beiText.setVisibility(View.VISIBLE);
                    } else if (reservation.getIsFareIncrease().equals("0")) {
                        tvTrivalCost.setText(reservation.getPrice() + "元");
                        beishuText.setText("");
                        beiText.setVisibility(View.GONE);
                    }
                } else if (dudgetBean.getReturn_code().equals("FAIL")) {
                }
            }
        });
    }


    public void getReservation() {
        GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
        dat = tvReservationTime.getText().toString();
        if (dat.equals("立即出发")) {//获取当前时间
            Date curDate = new Date(System.currentTimeMillis() + 1000);//当前时间的 一秒 后
            startTimeStamp = curDate.getTime() / 1000 + "";
        } else {
            startTimeStamp = calendar.getTime().getTime() / 1000 + "";//否则使用已选择的时间
        }

        UserNetWorks.getReservation(startTimeStamp, startLng, startLat, endLng, endLat, new Subscriber<ReservationBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(ReservationBean reservationBean) {
                ReservationBean.ReturnBodyBean reservation = reservationBean.getReturn_body();
                if (reservationBean.getReturn_code().equals("SUCCESS")) {
                    if (reservation.getIsFareIncrease().equals("1")) {
                        tvTrivalCost.setText(reservation.getPrice() + "元 X");
                        beishuText.setText("" + reservation.getFareIncreaseRate() + "");
                        beiText.setVisibility(View.VISIBLE);
                    } else if (reservation.getIsFareIncrease().equals("0")) {
                        tvTrivalCost.setText(reservation.getPrice() + "元");
                        beishuText.setText("");
                        beiText.setVisibility(View.GONE);
                    }
                } else if (reservationBean.getReturn_code().equals("FAIL")) {
                }
            }
        });
    }

    void getHiring() {
        GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
        dat = tvReservationTime.getText().toString();
        if (!tvEndLocation.getText().toString().equals("您要去哪里?")) {
            endLngStr = endLng;
            endLatStr = endLat;
            tvEndLoca = tvEndLocation.getText().toString();
        }

        if (dat.equals("立即出发")) {
            Date curDate = new Date(System.currentTimeMillis() + 1000);//当前时间的 一秒 后
            startTimeStamp = curDate.getTime() / 1000 + "";
        } else {
            startTimeStamp = calendar.getTime().getTime() / 1000 + "";//否则使用已选择的时间
        }

        if (startLng.equals("")) {
            startLng = globalPositionInfo.bdLocation.getLongitude() + "";
        }

        if (startLat.equals("")) {
            startLat = globalPositionInfo.bdLocation.getLatitude() + "";
        }
        UserNetWorks.getHiring(GYDate, startTimeStamp, startLng, startLat, tvStartLocation.getText().toString(), endLngStr, endLatStr, tvEndLoca, couponId, beishu, new Subscriber<VehicleBean>() {
            @Override
            public void onStart() {
                super.onStart();
                ((MainActivity) getActivity()).showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
                ((MainActivity) getActivity()).dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ((MainActivity) getActivity()).dissmisDialog();
            }

            @Override
            public void onNext(VehicleBean vehicleBean) {
                if (vehicleBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                    Intent intent = new Intent(getContext(), MapViewActivity.class);
                    intent.putExtra("userId", userid);
                    intent.putExtra("orderId", vehicleBean.getReturn_body());
                    intent.putExtra("startLng", startLng);
                    intent.putExtra("startLat", startLat);
                    intent.putExtra("endLngStr", endLngStr);
                    intent.putExtra("endLatStr", endLatStr);
                    intent.putExtra("orderType", "1");
                    startActivity(intent);
                    YHJText.setText("优惠劵");
                    couponId = "0";
                } else if (vehicleBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                }
            }
        });
    }

    void getReservationVehicle() {
        GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
        dat = tvReservationTime.getText().toString();
        if (!tvEndLocation.getText().toString().equals("您要去哪里?")) {
            endLngStr = endLng;
            endLatStr = endLat;
            tvEndLoca = tvEndLocation.getText().toString();
        }
        if (dat.equals("立即出发")) {
            Date curDate = new Date(System.currentTimeMillis() + 1000);//当前时间的 一秒 后
            startTimeStamp = curDate.getTime() / 1000 + "";
        } else {
            startTimeStamp = calendar.getTime().getTime() / 1000 + "";//否则使用已选择的时间
        }

        if (startLng.equals("")) {
            startLng = globalPositionInfo.bdLocation.getLongitude() + "";
        }

        if (startLat.equals("")) {
            startLat = globalPositionInfo.bdLocation.getLatitude() + "";
        }
        UserNetWorks.getReservationVehicle(startTimeStamp, startLng, startLat, tvStartLocation.getText().toString(), endLngStr, endLatStr, tvEndLoca, etPhoneNumber.getText().toString(), couponId, beishu, new Subscriber<VehicleBean>() {
            @Override
            public void onCompleted() {
                Log.e("getReservationVehicle", "成功");

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Log.e("getReservationVehicle", "失败");
            }

            @Override
            public void onNext(VehicleBean vehicleBean) {
                if (vehicleBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                    Intent intent = new Intent(getContext(), MapViewActivity.class);
                    intent.putExtra("userId", userid);
                    intent.putExtra("orderId", vehicleBean.getReturn_body());
                    intent.putExtra("startLng", startLng);
                    intent.putExtra("startLat", startLat);
                    intent.putExtra("endLngStr", endLngStr);
                    intent.putExtra("endLatStr", endLatStr);
                    startActivity(intent);
                    YHJText.setText("优惠劵");
                    couponId = "0";
                } else if (vehicleBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                }
            }
        });
    }

    void getDouble() {
        UserNetWorks.getDouble("", new Subscriber<DoubleBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

            }

            @Override
            public void onNext(DoubleBean doubleBean) {
                DoubleBean.ReturnBodyBean returnBodyBean = doubleBean.getReturn_body();
                if (returnBodyBean.getIsFareIncrease().equals("1")) {
                    beishu = returnBodyBean.getFareIncreaseRate() + "";
                    final AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(getContext());
                    normalDialog.setTitle("溢价提醒");
                    normalDialog.setMessage("临时调整价格" + returnBodyBean.getFareIncreaseRate() + "倍");
                    normalDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (PD == true) {
                                        getReservationVehicle();
                                    } else if (PD == false) {
                                        getHiring();
                                    }
                                }
                            });
                    normalDialog.setNegativeButton("关闭",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //...To-do
                                    dialog.dismiss();
                                }
                            });
                    // 显示
                    normalDialog.show();
                } else if (returnBodyBean.getIsFareIncrease().equals("0")) {
                    if (PD == true) {
                        getReservationVehicle();
                    } else if (PD == false) {
                        getHiring();
                    }
                }
            }
        });
    }
}